<?php
/**
 * Created by PhpStorm.
 * User: zhan
 * Date: 2018/7/30  10:52
 */

namespace app\admin\Controller;


class File extends Common {


    /*
    *	构造函数
    */
    function __construct(){
        parent::__construct();
    }

    public function index()
    {
        $pageParam = ['query' => []];
        $where = [];

        $file_name = input('file_name');
        if ($file_name != '') {
            $where['f.file_name'] = array('like', '%' . $file_name . '%');
            $pageParam['query']['file_name'] = $file_name;
        }

        $file_list = db('file')
            ->where($where)
            ->paginate(10,false,$pageParam);
        $page = $file_list->render();

        $this->assign('file_list',$file_list);
        $this->assign('file_name',$file_name);
        $this->assign('page',$page);
        return 	$this->fetch();
    }

    public function download()
    {
        $id = input('id');

        $data = db('file')
            ->where('id',$id)
            ->find();

        $file = IMG_PATH.$data['file_path'];
        $file_name_suffix = explode('.', $data['file_name']);
        $name = $file_name_suffix[0];

        $fileName = $name ? $name : pathinfo($file,PATHINFO_FILENAME);
        $filePath = $file;

        $fp = fopen($file,'rb');

        if(!$filePath || !$fp){
            header('HTTP/1.1 404 Not Found');
            echo "Error: 404 Not Found.(server file path error)";
            exit;
        }

        $fileName = $fileName .'.'. pathinfo($filePath,PATHINFO_EXTENSION);
        $encoded_filename = urlencode($fileName);
        $encoded_filename = str_replace("+", "%20", $encoded_filename);

        header('HTTP/1.1 200 OK');
        header( "Pragma: public" );
        header( "Expires: 0" );
        header("Content-type: application/octet-stream");
        header("Content-Length: ".$data['file_size']);
        header("Accept-Ranges: bytes");
        header("Accept-Length: ".$data['file_size']);

        $ua = $_SERVER["HTTP_USER_AGENT"];
        if (preg_match("/MSIE/", $ua)) {
            header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
        } else if (preg_match("/Firefox/", $ua)) {
            header('Content-Disposition: attachment; filename*="utf8\'\'' . $fileName . '"');
        } else {
            header('Content-Disposition: attachment; filename="' . $fileName . '"');
        }

        ob_end_clean(); //<--有些情况可能需要调用此函数
        // 输出文件内容
        fpassthru($fp);
        exit;
    }
}
